package com.macaku.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2024-01-12
 * Time: 21:24
 */
public class ShortLinkUtils {

    private static final String CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
    private static final int LINK_LENGTH = 6;

    public static final String LINK = "link:";

    public static String subCodeByString(String str) {
        int gap = str.length() / LINK_LENGTH;
        if(gap < 4) {
            return null;
        }
        StringBuilder subCode = new StringBuilder();
        for (int i = 0; i < LINK_LENGTH; i++) {
            int index = Integer.parseInt(str.substring(i * gap, i * gap + 4), 16);
            subCode.append(CHARSET.charAt(index % CHARSET.length()));
        }
        return subCode.toString();
    }

    public static String getShortCodeByURL(String url) {
        String hash = MD5Utils.md5(url + MD5Utils.getSalt());
        return subCodeByString(hash);
    }




}
